import json,re,random
from django.shortcuts import render
from django.views import View
from django.http import JsonResponse,QueryDict,HttpResponse
from django.views.decorators.csrf import csrf_exempt

from py2neo import Graph,Node,Relationship
# Create py2neo connection
graph = Graph(host='localhost',auth=('neo4j','123'))

nodesArr = []

# Create your views here.
class RestApi(View):
    @csrf_exempt
    def test(self,req):
        result = {
            'code':1,
            'msg':'数据查询到了',
            'data':{}
        }
        return JsonResponse(result)

def createNode(request):
    global graph
    a = Node("My_Person",name="test_node_Alice",age=12)
    b = Node("My_Person", name="test_node_Bob", age=10)
    c = Node("My_Person", name="test_node_Jiji", age=9)
    graph.create(a)
    graph.create(b)
    graph.create(c)

    ab = Relationship(a,"konws",b)
    ac = Relationship(a,"work_with",c)
    graph.create(ab)
    graph.create(ac)

    return JsonResponse(ab)

@csrf_exempt
def fetchNodes(request):
    # links_data = graph.run("MATCH (n:DE) -[*1..3] -> (p:EUP) RETURN n,p").data()
    # links_data = graph.run("match (n)-[]-(m) where n.Element_ID='100EG/001_A09' return m").data()
    # links = _get_links(links_data)
    # nodes_data = graph.run("MATCH (n:EUP) RETURN n").data()
    # print(nodes_data)
    # nodes = _get_all_nodes(nodes_data)
    rootId = eval(request.body.decode()).get('id')
    try:
        nodes_data = _fetchLeafAndChild(rootId)
        return JsonResponse({"data": nodes_data, "success": True}, safe=False)
    except:
        return JsonResponse({"data": [], "success": False}, safe=False)


def _fetchLeafAndChild(elementId):
    nodes_source = _fetchLeaf(elementId)
    nodes = []
    if len(nodes_source):
        for node in nodes_source:
            ElementId = node['id(m)']
            node['m']['key'] = ElementId
            newNodes = _fetchLeafAndChild(ElementId)
            if len(newNodes):
                node['m']['children'] = newNodes
            nodes.append(node['m'])
    return nodes

def _fetchLeaf(elementId):
    global graph
    sql = "match (n)<-[]-(m) where id(n)= "+str(elementId)+" return m,id(m)"
    nodes_source = graph.run(sql).data()
    # print(nodes_source)
    return  nodes_source

@csrf_exempt
def fetchStations(request):
    global graph
    try:
        sql = "MATCH (n) -[:NEXT] ->(s) return n,s"
        nodes_data = graph.run(sql).data()
        print(nodes_data)
        return JsonResponse({"data": nodes_data, "success": True}, safe=False)
    except:
        return JsonResponse({"data": [], "success": False}, safe=False)

@csrf_exempt
def fetchEquipments(request):
    global graph
    try:
        nodes_data = graph.run("MATCH (e) -[:USED_AT] ->(s:Station) return s,e").data()
        return JsonResponse({"data": nodes_data, "success": True}, safe=False)
    except:
        return JsonResponse({"data": [], "success": False}, safe=False)

@csrf_exempt
def fetchMPs(request):
    global graph
    try:
        nodes_data = graph.run("MATCH (n) -[:SUBELEMENT_OF] ->(s:Station) return s,n").data()
        return JsonResponse({"data": nodes_data, "success": True}, safe=False)
    except:
        return JsonResponse({"data": [], "success": False}, safe=False)

@csrf_exempt
def fetchDEs(request):
    global graph
    try:
        nodes_data = graph.run("MATCH (n) -[:CONSUMED_AT] ->(m:MP) return m,n").data()
        return JsonResponse({"data": nodes_data, "success": True}, safe=False)
    except:
        return JsonResponse({"data": [], "success": False}, safe=False)

def _get_links(links_data):
    """知识图谱关系数据获取"""
    links_data_str = str(links_data)
    links = []
    i = 1
    dict = {}
    # 正则匹配
    links_str = re.sub("[\!\%\[\]\,\。\{\}\-\:\'\(\)\>]", " ", links_data_str).split(' ')
    for link in links_str:
      if len(link) > 1:
          if i == 1:
              dict['source'] = link
          elif i == 2:
              dict['name'] = link
          elif i == 3:
              dict['target'] = link
              links.append(dict)
              dict = {}
              i = 0
          i += 1
    return links



